package com.miracle9.game.util;

import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class Encrypt {

    /**
     * MD5 32位加密
     *
     * @param sourceStr
     * @return
     */
    public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes("UTF-8"));
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * AES加密
     * @param value
     * @param key
     * @return
     * @throws Exception
     */
    public static String AESEncrypt(String value, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte[] raw = key.getBytes("UTF-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
        String base64 =  new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码
        return URLEncoder.encode(base64, "UTF-8");//URL加密
    }

    /**
     * AES加密
     * @param value
     * @param key
     * @return
     * @throws Exception
     */
    public static String AESEncodeEncrypt(String value, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte[] raw = key.getBytes("UTF-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
        String base64 = new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码
        return base64;
    }

    /**
     * AES加密 不进行URLEncoder
     * @param value
     * @param key
     * @return
     * @throws Exception
     */
    public static String AESUNURLEncrypt(String value, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte[] raw = key.getBytes("UTF-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
        return  new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码
    }

    /**
     * AES 解密
     * @param value
     * @param key
     * @param isDecodeURL
     * @return
     * @throws Exception
     */
    public static String AESDecrypt(String value, String key, boolean isDecodeURL) throws Exception {
        try {
            byte[] raw = key.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            if (isDecodeURL) value = URLDecoder.decode(value, "UTF-8");
            byte[] encrypted1 =  new BASE64Decoder().decodeBuffer(value);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "UTF-8");
            return originalString;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            String params = "{\"code\":10000,\"data\":[],\"protocal\":\"protocal_ws_separate_message\",\"status\":0}";
            String params1 = "KKKVD4859RgziNNTTOLbG8gyN5spcxdDAMPIvJOCwqIWkWHvXnw9Jr32nwRa2BY+5HIoJgMFuXXj\n" +
                    "fZ/WfCOgXGFoeWOYRUh9G15pVkgVuyEcZGpcHzATLhtb5nMZ15r9ey0gb6B4VzOGFhtipTembNsV\n" +
                    "dUqBF/4ebiCbVvyVfmXBGu3VlTa24YW+fWpMOW1J3xrGy5OwONK8/kxY7ZuTttiBotmPSJ/0HbNA\n" +
                    "SoHz9hx85eGb5gxxFAhjGz9McIkQWiCECiRz+CjcNlkf360FVJ4f5EBkpARSZxZGn+QuuY4=";
            String params2 = "{\"userId\":100085,\"gameType\":1}";


            JSONObject jsonObject = JSONObject.fromObject(params);

            System.out.println(jsonObject.get("code"));


            String signature = "44e9db8e809d8521a6d5772a47c526b6";

            String MD5_KEY = "1Xsg9YvTsJyL1w6n";
            String AES_KEY = "K1vsWt95wX7mXgoP";
            String jiami = AESUNURLEncrypt(params2, AES_KEY);
            System.out.println("加密："+jiami);
            String original = AESDecrypt(params1, AES_KEY, false);
            System.out.println("解密 => " + original);


            System.out.println(!"message".toString().startsWith("{"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
